//
//  HJPhotoPreviewView.m
//  KaiChat
//
//  Created by lx on 2023/10/30.
//

#import "HJPhotoPreviewView.h"
#import "HJPhotoItem.h"

#define kPhotoViewMaxScale 3

@interface HJPhotoPreviewView()<UIScrollViewDelegate, UIGestureRecognizerDelegate>


@end


@implementation HJPhotoPreviewView
 
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.bouncesZoom = YES;
        self.maximumZoomScale = kPhotoViewMaxScale;
        self.multipleTouchEnabled = YES;
        self.showsHorizontalScrollIndicator = YES;
        self.showsVerticalScrollIndicator = YES;

        self.delegate = self;
        if (@available(iOS 11.0, *)) {
            self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        
        [self addSubview:self.imageView];
        [self resizeImageView];
        [self.layer addSublayer:self.progressLayer];
        [self.progressLayer stopSpin];
    }
    return self;
}

- (HJProgressLayer *)progressLayer {
    if (!_progressLayer) {
        _progressLayer = [[HJProgressLayer alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _progressLayer.hidden = YES;
    }
    return _progressLayer;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[SDAnimatedImageView alloc] init];
        _imageView.backgroundColor = UIColor.blackColor;
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
    }
    return _imageView;
}

- (void)resizeImageView {
    if (_imageView.image) {
        CGSize imageSize = _imageView.image.size;
        CGFloat width = self.frame.size.width;
        CGFloat height = width * (imageSize.height / imageSize.width);
        CGRect rect = CGRectMake(0, 0, width, height);
        
        _imageView.frame = rect;
        if (height <= self.bounds.size.height) {
            _imageView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
        } else {
            _imageView.center = CGPointMake(self.bounds.size.width/2, height/2);
        }
        if (width / height > 2) {
            self.maximumZoomScale = self.bounds.size.height / height;
        }
    } else {
        CGFloat width = self.frame.size.width;
        _imageView.frame = CGRectMake(0, 0, width, width * 2.0 / 3);
        _imageView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    }
    self.contentSize = _imageView.frame.size;
    self.zoomScale = 1.f;
}

- (void)setItem:(HJPhotoItem *)item {
    _item = item;
    
    if (item == nil) {
        self.imageView.image = nil;
        item.image = nil;
        [self resizeImageView];
        return;
    }
    
    UIImage *image = nil;
    if (item.image) {
        image = item.image;
    } else {
        if (item.localPath.length && [[NSFileManager defaultManager] fileExistsAtPath:item.localPath]) {
            image = [UIImage imageWithContentsOfFile:item.localPath];
        }
    }
    
    if (image) {
        item.image = image;
        self.imageView.image = image;
        item.finished = YES;
        [self resizeImageView];
        return;
    }
    
    if (item.originalUrl) {
        [self loadOriginalImageWithURL:item.originalUrl.URL];
    } else {
        [self loadOriginalImageWithURL:item.thumbUrl.URL];
    }
}

- (void)loadOriginalImageWithURL:(NSURL *)URL{
    NSLog(@"item.originalUrl = %@", URL);
    [self.progressLayer startSpin];
    TJWeakify(self)
    [self.imageView tj_setImageWithURL:URL placeholderImage:_item.thumbImage ?: [UIImage imageNamed:loadImageDefaultImageName] completed:^(UIImage * _Nullable image) {
        NSLog(@"加载原图 = %@", image);
        [weakself.progressLayer stopSpin];
        weakself.item.finished = YES;
        if (image && image.size.width) {
            weakself.item.image = image;
            [weakself resizeImageView];
        }
    }];
}

- (void)queryCacheThumbImageForURL:(NSURL *)URL completed:(void (^)(UIImage *image))completed {
    NSString *cacheKey = [[SDWebImageManager sharedManager] cacheKeyForURL:URL];
    [[SDImageCache sharedImageCache] queryImageForKey:cacheKey options:0 context:nil cacheType:SDImageCacheTypeAll completion:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
        if (completed) completed(image);
    }];
}

- (void)reload {
    
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
    _progressLayer.frame = CGRectMake((self.frame.size.width - 40) * 0.5, (self.frame.size.height - 40) * 0.5, 40, 40);
}


- (BOOL)isScrollViewOnTopOrBottom {
    CGPoint translation = [self.panGestureRecognizer translationInView:self];
    if (translation.y > 0 && self.contentOffset.y <= 0) {
        return YES;
    }
    CGFloat maxOffsetY = floor(self.contentSize.height - self.bounds.size.height);
    if (translation.y < 0 && self.contentOffset.y >= maxOffsetY) {
        return YES;
    }
    return NO;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer == self.panGestureRecognizer) {
        if (gestureRecognizer.state == UIGestureRecognizerStatePossible) {
            if ([self isScrollViewOnTopOrBottom]) {
                return NO;
            }
        }
    }
    return YES;
}

#pragma mark - ScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return _imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView {
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    
    _imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                    scrollView.contentSize.height * 0.5 + offsetY);
}


@end
